package com.seagox.desk.config;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.SocketIOClient;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.util.HashMap;
import java.util.UUID;

@Component
public class RedisSub implements MessageListener {
	
    @Resource
    private ClientCache clientCache;
    
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void onMessage(Message message, byte[] pattern) {
    	String body = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        try {
        	JSONObject data = JSONObject.parseObject(body);
            String channel = (String) redisTemplate.getValueSerializer().deserialize(message.getChannel());
            if (!StringUtils.isEmpty(channel)) {
            	JSONArray target = data.getJSONArray("target");
            	String event = data.getString("event");
            	for(int i=0;i<target.size();i++) {
            		HashMap<UUID, SocketIOClient> userClient = clientCache.getUserClient(target.getString(i));
                    if (userClient != null && !userClient.isEmpty()) {
                    	userClient.forEach((uuid, socketIOClient) -> {
                            socketIOClient.sendEvent(event, JSONObject.parse(body));
                        });
                    }
            	}
            }
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
}
